package com.homework6;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class client {
    public static void main(String[] args) throws IOException {
        Socket serverSocket = new Socket("127.0.0.1",8888);
            try {
                Thread.sleep(1000);
                System.out.println("请输入消息，按Enter键发送");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            InputStream inputStream = serverSocket.getInputStream();
            OutputStream outputStream = serverSocket.getOutputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));

            //开启线程1接受用户端发来的消息
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        String str = null;
                        try {
                            str = bufferedReader.readLine();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (str.equals("88")) {
                            System.out.println("聊天结束.....");
                            System.exit(0);
                        } else {
                            System.out.println("来自客户端:" + str);
                        }
                    }
                }
            }.start();
            //开启线程2向用户端发来的消息
            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            System.out.println("请输入消息:");
                            String msg = new Scanner(System.in).nextLine();
                            //向服务器发送消息
                            bufferedWriter.write(msg);
                            //写完换行
                            bufferedWriter.newLine();
                            bufferedWriter.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }
    }
